package com.szl.yeb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szl.yeb.exception.CustomException;
import com.szl.yeb.mapper.DepartmentMapper;
import com.szl.yeb.entity.Department;
import com.szl.yeb.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.szl.yeb.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szl.yeb.utils.MybatisPlusUtil;

import java.util.List;

/**
 * (Department)表服务实现类
 *
 * @author szl
 * @since 2022-08-24 16:21:23
 */
@Service("departmentService")
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public PageResult getPage(Integer currentPage, Integer size, Department department) {
        Page<Department> page = new Page<>(currentPage, size);

        QueryWrapper<Department> queryWrapper = MybatisPlusUtil.queryWrapperBuilder(department);

        this.page(page, queryWrapper);

        return new PageResult((int) page.getTotal(), page.getRecords());
    }

    @Override
    public List<Department> getDepartmentsWithChildren() {
        return departmentMapper.selectDepartmentsWithChildren(-1);
    }

    @Override
    public Integer addDepartment(Department department) {
        return departmentMapper.insertDepartment(department);
    }

    @Override
    public Integer deleteDepartment(Integer did) {
        Department department = new Department();
        departmentMapper.deleteDepartment(department.setId(did));
        Integer result = department.getResult();
        if (result == -1) {
            throw new CustomException("该部门存在员工，无法删除");
        }
        if (result == -2) {
            throw new CustomException("该部门存在子部门，无法删除");
        }
        return result;
    }
}

